package cn.quan.evernote;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;

/**
 * 
 * @author yunfeng.quan@gmail.com
 *
 */

final public class Picmo extends Activity {
	//view
	private CameraView mCameraView;//main view
	private InfoView mInfoView;//information view
	
	private ProgressDialog mWaitLoginDialog;
	private AlertDialog.Builder mLoginDialog;
	private Handler mHandler = new Handler();

	//username / password
	private String mUsername ;
	private String mPassword ;
	//setting
	private Setting mSet;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "*onCreate");
		super.onCreate(savedInstanceState);
		///setting
		loadSetting();//wait 500msec
		///view
		//set window
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//initialize dialog
		initDialogView();
		// set view
		mCameraView = new CameraView(Picmo.this);
		mCameraView.lock();
		mInfoView = new InfoView(Picmo.this);
		mCameraView.setInfoView(mInfoView);
		///service
		//start service
		Intent intent = new Intent(Picmo.this,PicmoService.class);
		startService(intent);//为了结束绑定以后不马上结束Service
		bindService(intent,mConnection,Context.BIND_AUTO_CREATE);
		notifyMessage("connect service");
		
		//last
		setContentView(mCameraView);
		addContentView(mInfoView, new LayoutParams  
				(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mPicmoService == null){
			//do nothing
		}else{
			try {
				//Log.d(TAG, "*onDestroy/exit sended.");
				mPicmoService.exit();//通知服务，当完成进行中作业以后结束自己
			} catch (RemoteException e) {
				e.printStackTrace();
			}//
			unbindService(mConnection);		
		}
		Log.d(TAG, "*onDestroy");
	}
	///common function
	private void loadSetting(){
		mSet = new Setting();//need wait some time. maybe 200ms
		try {
			Thread.sleep(200);//不等等的话，好像容易出错
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//load default setting
		mUsername = mSet.getUser();
		mPassword = mSet.getPassword();
	}
	private boolean isFrist(){
		if(mSet == null){
			Log.e(TAG,"*setting set is null");
		}
		if(mSet.isFrist()){
			return true;
		}else{
			return false;
		}
	}
	//生成Dialog对象
	// 限制：
	private void createWaitLoginDialog(){
		//login dialog
		mWaitLoginDialog = new ProgressDialog(Picmo.this);
		mWaitLoginDialog.setTitle("Login");
		mWaitLoginDialog.setMessage("Please wait 30 seconds.");
	}
	// param message:information.
	private void createLoginDialog(String message){
		//regist dialog
		if(mLoginDialog == null){
			LayoutInflater factory = LayoutInflater.from(Picmo.this);
			final View loginDialogView = factory.inflate(R.layout.regist, null);
			mLoginDialog = new AlertDialog.Builder(Picmo.this);
			mLoginDialog.setTitle("Login to www.Evernote.com"); //
			if(message.length()>0){
				mLoginDialog.setMessage(message);
			}else{
				mLoginDialog.setMessage(null);
			}
			mLoginDialog.setView(loginDialogView); //custom view
			mLoginDialog.setPositiveButton("Regist",new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mUsername = ((EditText)loginDialogView.findViewById(R.id.txtUser)).getText().toString();
					mPassword = ((EditText)loginDialogView.findViewById(R.id.txtPassword)).getText().toString();
					if(mUsername.length()==0 || mPassword.length() == 0){
						login("Can not be Empty.");//re login
					}else{
						try {
							if(mPicmoService != null){
								mWaitLoginDialog.show();
								mPicmoService.loginEvernote(mUsername, mPassword);
							}else{
								Log.e(TAG,"*picmoService is null.");
							}
						} catch (RemoteException e) {
							e.printStackTrace();
						}
					}
				}
			});
			mLoginDialog.setNeutralButton("Exit",new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			mLoginDialog.create();
		}else{
			if(message.length()>0){
				mLoginDialog.setMessage(message);
			}else{
				mLoginDialog.setMessage(null);
			}
		}
		//return registDialog;

	}
	private void initDialogView(){
		createWaitLoginDialog();
		createLoginDialog("");
	}
	private void login(String message){
		final String msg=message;
		if(mPicmoService == null){
			Log.e(TAG,"*picmoService is null");
			return;
		}
		mHandler.post(new Runnable(){

			@Override
			public void run() {
    			if(isFrist()){
    				mCameraView.lock();
    				createLoginDialog(msg);
    				mLoginDialog .show();
    			}else{
    				mCameraView.unlock();
					try {
						if(mPicmoService != null){
							mPicmoService.loginEvernote(mUsername, mPassword);
						}else{
							Log.e(TAG,"*picmoService is null.");
						}
					} catch (RemoteException e) {
						e.printStackTrace();
					}
    			}
				
			}
		});
	}
	private void notifyMessage(String message){
		final String msg=message;
		if(mInfoView == null){
			Log.e(TAG,"*mInfoView is null");
			return;
		}
		mHandler.post(new Runnable(){
			@Override
			public void run() {
				mInfoView.notifyMessage(msg);
			}
		});
	}
	private void notifyUploadCount(){
		if(mInfoView == null){
			Log.e(TAG,"*mInfoView is null");
			return;
		}
		mHandler.post(new Runnable(){
			@Override
			public void run() {
				mInfoView.notifyDec();
			}
		});
	}
	///memu
	private static final int MENU_SHUTTER = Menu.FIRST + 1;
	private static final int MENU_LOGIN = Menu.FIRST + 2;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, MENU_SHUTTER, Menu.NONE, "Shutter");
		menu.add(Menu.NONE, MENU_LOGIN, Menu.NONE, "Login");
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean rc = true;
		switch (item.getItemId()) {
		case MENU_SHUTTER:
			mCameraView.autoFocus();
			break;
		case MENU_LOGIN:
			mSet.clearLoginInfo();//clear user info
			login("");
			break;
		default:
			rc = super.onOptionsItemSelected(item);
			break;
		}
		return rc;
	}
	
	///picmoservice interface
	private IPicmoService mPicmoService;
	private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder ibinder) {
        	mPicmoService = IPicmoService.Stub.asInterface(ibinder);
    		try {
    			mPicmoService.registerCallback(mRmiPicmo);
    			if(mCameraView != null){
    				mCameraView.setPicmoService(mPicmoService);//TODO 顺序相关
    			}else{
    				Log.e(TAG,"*mCameraView is null.");
    			}
				notifyMessage("Logging");
    			login("");
    		} catch (RemoteException e) {
    			Log.e(TAG,e.toString());
    			e.printStackTrace();
    		}
        }

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
		}
    };
    private IPicmo mRmiPicmo=new IPicmo.Stub() {

		@Override
		public void resLogin(boolean result, int errcode, String errmessage)
				throws RemoteException {
			if(mWaitLoginDialog.isShowing()){
				mWaitLoginDialog.dismiss();
			}
			if(result == false){//login fail
				notifyMessage("Login faild.<"+errmessage+">");
				switch(errcode){
				case SimpleEvernote.err_login_user:
					createLoginDialog("该用户不存在<"+mUsername+">");
					break;
				case SimpleEvernote.err_login_password:
					createLoginDialog("密码不正确<"+mUsername+">");
					break;
				case SimpleEvernote.err_network_host:
					createLoginDialog("服务器连接错误。请检查网络设置。");
					break;
				default:
					createLoginDialog("不明原因登录失败。");
					break;
				}
				login(errmessage);//re login
				
			}else{
				notifyMessage("Login successful.");
				mCameraView.unlock();
				//true
				mSet.setUser(mUsername);
				mSet.setPassword(mPassword);
				notifyMessage("Saved login information.");
			}
		}

		@Override
		public void resUpload(boolean result, int errcode, String errmessage)
				throws RemoteException {
			// TODO Auto-generated method stub
			notifyUploadCount();
			if(result == false){//upload fail
				switch(errcode){
				case SimpleEvernote.err_upload_user:
					notifyMessage("upload falid.该用户不存在");
					break;
				case SimpleEvernote.err_upload_password:
					notifyMessage("upload falid.密码不正确");
					break;
				case SimpleEvernote.err_upload_quota:
					notifyMessage("upload falid.超过使用容量");
					break;
				case SimpleEvernote.err_network_host:
					notifyMessage("upload falid.服务器链接错误");
					break;
				default:
					notifyMessage("upload falid.不明原因");
					break;
				}
			}else{
				notifyMessage("Upload successful.");
			}
		}
	};

	///setting
	public class Setting {
		private SharedPreferences mySetting;
		private Editor editor;
		public Setting(){
			mySetting = getPreferences(Context.MODE_PRIVATE);
		}
		public boolean isFrist(){
			String user = mySetting.getString(set_user_name,"");
			if(user.length()==0){
				return true;
			}
			return false;
		}
		public void clearLoginInfo(){
			setUser("");
		}
		public void setUser(String username){
			editor = mySetting.edit();
			editor.putString(set_user_name, username);
			editor.commit();
		}
		public String getUser(){
			return mySetting.getString(set_user_name,"");
		}
		public void setPassword(String pwd){
			editor = mySetting.edit();
			editor.putString(set_password, pwd);
			editor.commit();
		}
		public String getPassword(){
			return mySetting.getString(set_password,"");
		}
		private final static String set_user_name = "user";
		private final static String set_password = "password";
	}


	private final String TAG = "**picmo**";

}
